<template>
  <n-layout v-if="status == 0">
    <n-layout-header bordered>
      <Header></Header>
    </n-layout-header>
    <n-layout-content content-style="height:calc(100vh - 122px)">
      <n-layout
        content-style="height:calc(100vh - 122px)"
        has-sider
        sider-placement="left"
      >
        <n-layout-sider
          :width="250"
          collapse-mode="width"
          :collapsed-width="0"
          bordered
          show-trigger="bar"
        >
          <outlineComp></outlineComp>
        </n-layout-sider>
        <n-layout-content content-style="padding:24px;">
          <toolsComp></toolsComp>
          <n-divider style="margin: 12px !important"></n-divider>
          <n-watermark
            content="核心机密"
            cross
            selectable
            :font-size="16"
            :line-height="16"
            :width="192"
            :height="128"
            :x-offset="12"
            :y-offset="28"
            :rotate="-15"
            font-color="rgba(128,128,128,0.1)"
          >
            <div
              :class="['component-item']"
              :key="formStore.selectComponent().prop"
              v-if="formStore.selectComponent()"
            >
              <n-form-item
                :required="formStore.selectComponent().required == 1"
                :label="
                  formStore.selectComponent().name ||
                  formStore.selectComponent().prop
                "
                style="flex: 1"
              >
                <component
                  :is="
                    renderComp(
                      formStore.selectComponentIndex,
                      formStore.selectComponent().type
                    )
                  "
                ></component>
              </n-form-item>
              <div v-if="showVerify" class="verify" style="margin-bottom: 12px">
                <div class="title">审核</div>
                <div class="content">
                  <div
                    readonly
                    placeholder="请输入分数"
                    button-placement="both"
                    style="width: 160px; margin-bottom: 12px; text-align: left"
                  >
                    <span style="font-weight: bold; font-size: 16px">
                      {{
                        formStore.submitInfo[formStore.selectComponent().prop]
                          ? formStore.submitInfo[
                              formStore.selectComponent().prop
                            ].verifyScore
                          : 0
                      }}</span
                    >
                    分
                  </div>
                  <div style="color: red">
                    {{
                      formStore.submitInfo[formStore.selectComponent().prop]
                        ? formStore.submitInfo[formStore.selectComponent().prop]
                            .verifyText
                        : ""
                    }}
                  </div>
                  <!-- <n-input
                  style="color: red !important"
                  readonly
                  placeholder=""
                  type="textarea"
                  v-model:value="
                    formStore.submitInfo[formStore.selectComponent().prop]
                      .verifyText
                  "
                ></n-input> -->
                </div>
              </div>
              <n-divider style="margin: 0 !important"></n-divider></div
          ></n-watermark>
        </n-layout-content>
      </n-layout>
      <!-- <formBuilder ref="formBuilderRef" :schema="(schema as any)"></formBuilder> -->
    </n-layout-content>
    <n-layout-footer bordered>
      <div v-if="!disableFooter" class="footer">
        <n-space>
          <n-button
            @click="handleTmpSave"
            style="width: 120px"
            type="warning"
            secondary
            stronger
            >暂存结果</n-button
          >
          <n-button
            v-if="!showVerify"
            @click="handleSave"
            style="width: 120px"
            type="primary"
            secondary
            stronger
            >提交结果</n-button
          >
          <n-button
            v-else
            @click="handleUpdate"
            style="width: 120px"
            type="error"
            secondary
            stronger
            >重新提交</n-button
          >
        </n-space>
      </div>
    </n-layout-footer>
  </n-layout>
  <div class="page" v-else-if="status == -1">
    <div class="loader"></div>
    <div>正在加载中</div>
  </div>
  <div class="page" v-else-if="status == 5">
    <n-result
      status="403"
      title="禁止访问"
      description="您没有填写此表单的权限，请与管理员联系"
    >
      <template #footer>
        <n-button @click="handleMessage">申请权限</n-button>
        <n-button @click="handleReLogin" type="primary">更改账号</n-button>
      </template>
    </n-result>
  </div>
  <div class="page" v-else-if="status == 2">
    <n-result
      status="success"
      title="审核通过"
      description="您已审核通过，无需再更改"
    >
      <template #footer>
        <n-button @click="showPreview">查看已填写内容</n-button>
      </template>
    </n-result>
  </div>
  <div class="page" v-else-if="status == 1">
    <n-result
      status="info"
      title="已完成表单"
      description="您已经完成本表单的填写，请等待管理员批改"
    >
      <template #footer>
        <n-space justify="center">
          <n-button @click="handleMessage" type="warning"
            >申请重新填写</n-button
          >
        </n-space>
      </template>
    </n-result>
  </div>
  <div class="page" v-else-if="status == 3">
    <n-result
      status="error"
      title="审核失败"
      description="您填写的表单有需要更改的地方，请重新填写"
    >
      <template #footer>
        <n-button @click="handleReEdit">重新修改</n-button>
      </template>
    </n-result>
  </div>
</template>

<script lang="ts" setup>
import Header from "./header.vue";
import { ref, onMounted, computed, h } from "vue";
import { useFormStore } from "@/store/form";
import { useRoute } from "vue-router";
import { useUserStore } from "@/store/user";
import formBuilder from "@/components/form-builder/index.vue";
import {
  getRecordFormByPerson,
  saveRecordForm,
  updateRecordForm,
} from "@/api/form";
import { useMessage, useDialog } from "naive-ui";
import { v1 } from "uuid";
import outlineComp from "./components/outline/index.vue";
import toolsComp from "./components/tools/index.vue";
import { useMainStore } from "@/store";
const components = import.meta.glob(
  "../../pages/form-editor/components/**/index.vue",
  {
    eager: true,
  }
);
console.log(components);
const mainStore = useMainStore();
const formBuilderRef = ref();
const userStore = useUserStore();
const formStore = useFormStore();
const route = useRoute();
const message = useMessage();
const dialog = useDialog();
const status = ref(-1);
const recordId = ref(-1);
const showVerify = ref(false);
const disableFooter = ref(false);
const renderComp = (index: number, type: string) => {
  // console.log(`../form-editor/components/${type}/index.vue`);
  return h(
    components[`../form-editor/components/${type}/index.vue`]["default"],
    {
      prop: formStore.formInfo.content[index].prop,
      ...formStore.formInfo.content[index].props,
      value: formStore.formInfo.content[index].default,
      onUpdateValue: (val) => (formStore.formInfo.content[index].default = val),
    }
  );
};
const handleUpdate = () => {
  let i = 0;
  for (let key in formStore.submitInfo) {
    console.log(formStore.submitInfo[key]);
    if (formStore.submitInfo[key].isComplete) {
      i++;
    }
  }
  if (i < formStore.formInfo.content.length) {
    dialog.error({
      title: "提交失败",
      content: `你还有${
        formStore.formInfo.content.length - i
      }题未完成，请继续填写`,
      positiveText: "好的",
    });
    return;
  }
  dialog.info({
    title: "确认重新提交",
    content: `提交后将会把结果同步至线上并通知管理员，请确认`,
    positiveText: "确认提交",
    onPositiveClick() {
      updateRecordForm({
        id: recordId.value,
        content: formStore.submitInfo,
        status: 1,
      })
        .then((res2) => {
          message.success("修改成功");
        })
        .catch((e) => {
          message.error(`修改失败:${e}`);
          console.log(e);
        });
    },
  });
};
const handleSave = () => {
  // console.log(Object.keys(formStore.submitInfo));
  let i = 0;
  for (let key in formStore.submitInfo) {
    console.log(formStore.submitInfo[key]);
    if (formStore.submitInfo[key].isComplete) {
      i++;
    }
  }
  if (i < formStore.formInfo.content.length) {
    dialog.error({
      title: "提交失败",
      content: `你还有${
        formStore.formInfo.content.length - i
      }题未完成，请继续填写`,
      positiveText: "好的",
    });
    return;
  }
  dialog.info({
    title: "确认提交",
    content: `提交后将会把结果同步至线上并通知管理员，请确认`,
    positiveText: "确认提交",
    onPositiveClick() {
      saveRecordForm({
        from_form: route.query.id,
        pid: v1(),
        content: formStore.submitInfo,
        status: 1,
      })
        .then((res2) => {
          message.success("保存成功");
          setTimeout(() => {
            status.value = 1;
          }, 300);
        })
        .catch((e) => {
          message.error(`保存失败:${e}`);
          console.log(e);
        });
    },
  });
};

const handleTmpSave = () => {
  const pid = route.query.id as string;
  localStorage.setItem(pid, JSON.stringify(formStore.submitInfo));
  message.success("暂存本地成功");
};
const handleReEdit = () => {
  status.value = 0;
  showVerify.value = true;
};
const showPreview = () => {
  disableFooter.value = true;
  status.value = 0;
};
const handleMessage = () => {
  message.success("通知成功");
};
const handleReLogin = () => {
  mainStore.showLogin = true;
};
onMounted(async () => {
  const userInfo = await userStore.updateUserInfo();
  const id = route.query.id as string;
  formStore.pid = id;
  await formStore.getForm();
  console.log(formStore.formInfo.joinUsers, userInfo);
  if (
    !formStore.formInfo.joinUsers.find((item) => item.id == userInfo.id) &&
    userInfo.id != 1
  ) {
    status.value = 5;
    return;
  }
  getRecordFormByPerson({ pid: id, userId: userInfo.id }).then((res: any) => {
    console.log(res);
    if (res) {
      status.value = res.status;
      formStore.submitInfo = res.content;
      recordId.value = res.id;
    } else {
      status.value = 0;
      const tmpData = localStorage.getItem(id);
      if (tmpData) {
        formStore.submitInfo = JSON.parse(tmpData);
      } else {
        formStore.submitInfo = {};
      }
    }
  });

  // if (tmpData) {
  //   dialog.info({
  //     title: "恢复数据",
  //     content: "检测到上次备份的数据,是否恢复?",
  //     positiveText: "恢复",
  //     negativeText: "重新填写",
  //     onPositiveClick() {
  //       formStore.submitInfo = JSON.parse(tmpData);
  //     },
  //   });
  // }
});
</script>

<style lang="scss" scoped>
.footer {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 24px;
  justify-content: flex-end;
}
.page {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  background-color: #fff;
}
.dark .page {
  background-color: #000;
}
.loader {
  border: 8px solid #f3f3f3; /* Light grey */
  border-top: 8px solid #63e2b7; /* Blue */
  border-radius: 50%;
  width: 120px;
  height: 120px;
  animation: spin 2s linear infinite;
  margin-bottom: 24px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
